#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
文本补充结果解析器模块
负责解析DeepSeek文本大模型返回的补充分析结果，提供标准化的数据格式和访问接口
"""

import json
import re
import logging
from typing import Dict, Any, List, Optional
from datetime import datetime

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
)
logger = logging.getLogger(__name__)


class SupplementResultParser:
    """
    文本补充结果解析器
    解析文本大模型返回的补充分析结果，提供标准化的数据访问接口
    """
    
    def __init__(self):
        """
        初始化解析器
        """
        logger.info("SupplementResultParser初始化完成")
    
    def parse(self, raw_response: Dict[str, Any]) -> Dict[str, Any]:
        """
        解析原始响应结果
        
        Args:
            raw_response: 文本大模型返回的原始响应结果
            
        Returns:
            dict: 解析后的结构化结果
        """
        try:
            # 提取模型响应内容
            if 'choices' in raw_response and len(raw_response['choices']) > 0:
                message = raw_response['choices'][0].get('message', {})
                content = message.get('content', '')
                
                # 解析JSON格式的结果
                parsed_result = self._extract_json_result(content)
                
                # 验证并标准化结果格式
                standardized_result = self._standardize_result(parsed_result)
                
                # 添加解析元数据
                standardized_result['metadata'] = {
                    'parsed_at': datetime.now().isoformat(),
                    'raw_content_length': len(content),
                    'parse_success': True
                }
                
                return standardized_result
            
            logger.error("无效的API响应格式: 缺少choices字段或为空")
            return self._create_error_result("无效的API响应格式")
            
        except Exception as e:
            logger.error(f"解析响应结果时发生错误: {str(e)}")
            return self._create_error_result(f"解析错误: {str(e)}")
    
    def _extract_json_result(self, content: str) -> Dict[str, Any]:
        """
        从响应内容中提取JSON结果
        
        Args:
            content: 响应内容文本
            
        Returns:
            dict: 解析的JSON结果
        """
        try:
            # 首先尝试直接解析整个内容
            return json.loads(content)
        except json.JSONDecodeError:
            logger.warning("响应内容不是有效的JSON，尝试提取JSON部分")
            
            # 尝试提取花括号之间的内容
            json_match = re.search(r'\{[\s\S]*\}', content)
            if json_match:
                try:
                    return json.loads(json_match.group())
                except json.JSONDecodeError:
                    logger.error("无法从响应中提取有效的JSON")
            
            # 如果都失败，返回一个基础结构，包含原始文本作为整体分析
            return {
                "supplement_fields": {},
                "overall_analysis": content.strip()
            }
    
    def _standardize_result(self, result: Dict[str, Any]) -> Dict[str, Any]:
        """
        标准化结果格式
        
        Args:
            result: 解析的原始结果
            
        Returns:
            dict: 标准化后的结果
        """
        standardized = {
            "supplement_fields": {},
            "overall_analysis": "",
            "parsed_fields_count": 0,
            "high_confidence_fields": []
        }
        
        # 处理supplement_fields
        supplement_fields = result.get('supplement_fields', {})
        for field_name, field_data in supplement_fields.items():
            if isinstance(field_data, dict):
                # 确保必要字段存在
                standardized_field = {
                    'value': field_data.get('value', ''),
                    'confidence': max(0, min(100, field_data.get('confidence', 0))),  # 确保0-100范围
                    'reasoning': field_data.get('reasoning', ''),
                    'field_name': field_name
                }
                
                standardized["supplement_fields"][field_name] = standardized_field
                standardized["parsed_fields_count"] += 1
                
                # 记录高置信度字段（>80%）
                if standardized_field['confidence'] > 80:
                    standardized["high_confidence_fields"].append(field_name)
        
        # 处理整体分析
        standardized["overall_analysis"] = result.get('overall_analysis', '').strip()
        
        return standardized
    
    def _create_error_result(self, error_message: str) -> Dict[str, Any]:
        """
        创建错误结果
        
        Args:
            error_message: 错误信息
            
        Returns:
            dict: 包含错误信息的结果
        """
        return {
            "supplement_fields": {},
            "overall_analysis": "",
            "parsed_fields_count": 0,
            "high_confidence_fields": [],
            "metadata": {
                "parsed_at": datetime.now().isoformat(),
                "parse_success": False,
                "error_message": error_message
            }
        }
    
    def get_field_by_name(self, parsed_result: Dict[str, Any], field_name: str) -> Optional[Dict[str, Any]]:
        """
        根据字段名获取特定补充字段的信息
        
        Args:
            parsed_result: 解析后的结果
            field_name: 字段名
            
        Returns:
            dict: 字段信息，如果不存在则返回None
        """
        return parsed_result.get('supplement_fields', {}).get(field_name)
    
    def get_high_confidence_fields(self, parsed_result: Dict[str, Any]) -> List[str]:
        """
        获取高置信度字段列表
        
        Args:
            parsed_result: 解析后的结果
            
        Returns:
            list: 高置信度字段名列表
        """
        return parsed_result.get('high_confidence_fields', [])
    
    def get_overall_analysis(self, parsed_result: Dict[str, Any]) -> str:
        """
        获取整体分析内容
        
        Args:
            parsed_result: 解析后的结果
            
        Returns:
            str: 整体分析内容
        """
        return parsed_result.get('overall_analysis', '')
    
    def get_parsed_fields_count(self, parsed_result: Dict[str, Any]) -> int:
        """
        获取解析的字段数量
        
        Args:
            parsed_result: 解析后的结果
            
        Returns:
            int: 字段数量
        """
        return parsed_result.get('parsed_fields_count', 0)
    
    def validate_result(self, parsed_result: Dict[str, Any]) -> bool:
        """
        验证解析结果的有效性
        
        Args:
            parsed_result: 解析后的结果
            
        Returns:
            bool: 结果是否有效
        """
        # 检查必要字段是否存在
        required_fields = ['supplement_fields', 'overall_analysis', 'parsed_fields_count']
        for field in required_fields:
            if field not in parsed_result:
                return False
        
        # 检查metadata字段的解析状态
        metadata = parsed_result.get('metadata', {})
        if isinstance(metadata, dict) and metadata.get('parse_success') is False:
            return False
        
        return True
    
    def merge_with_vision_results(self, parsed_result: Dict[str, Any], vision_results: Dict[str, Any]) -> Dict[str, Any]:
        """
        将解析后的文本补充结果与视觉分析结果合并
        
        Args:
            parsed_result: 解析后的文本补充结果
            vision_results: 视觉分析结果
            
        Returns:
            dict: 合并后的结果
        """
        try:
            # 创建视觉结果的深拷贝以避免修改原始数据
            import copy
            merged_results = copy.deepcopy(vision_results)
            
            # 确保analysis字段存在
            if 'analysis' not in merged_results:
                merged_results['analysis'] = {}
            
            # 添加文本补充结果
            merged_results['text_supplement'] = {
                'timestamp': datetime.now().isoformat(),
                'overall_analysis': parsed_result.get('overall_analysis', ''),
                'parsed_fields_count': parsed_result.get('parsed_fields_count', 0),
                'high_confidence_fields': parsed_result.get('high_confidence_fields', []),
                'supplemented_fields': []
            }
            
            # 合并补充字段
            supplement_fields = parsed_result.get('supplement_fields', {})
            for field_name, field_data in supplement_fields.items():
                current_value = merged_results['analysis'].get(field_name, {})
                current_confidence = current_value.get('confidence', 0) if isinstance(current_value, dict) else 0
                supplement_confidence = field_data.get('confidence', 0)
                
                # 只更新置信度更高的结果
                if supplement_confidence > current_confidence:
                    # 保存原始值（如果有）
                    original_value = None
                    original_confidence = None
                    if isinstance(current_value, dict):
                        original_value = current_value.get('value')
                        original_confidence = current_value.get('confidence')
                    
                    # 更新为新值
                    merged_results['analysis'][field_name] = {
                        'value': field_data.get('value'),
                        'confidence': supplement_confidence,
                        'source': 'text_supplement',
                        'reasoning': field_data.get('reasoning', '')
                    }
                    
                    # 记录被补充的字段
                    merged_results['text_supplement']['supplemented_fields'].append({
                        'field_name': field_name,
                        'original_value': original_value,
                        'original_confidence': original_confidence,
                        'new_value': field_data.get('value'),
                        'new_confidence': supplement_confidence
                    })
            
            logger.info(f"成功合并结果，补充了 {len(merged_results['text_supplement']['supplemented_fields'])} 个字段")
            return merged_results
            
        except Exception as e:
            logger.error(f"合并结果失败: {str(e)}")
            # 发生错误时返回原始视觉结果，并添加错误信息
            vision_results['text_supplement_error'] = str(e)
            vision_results['text_supplement_timestamp'] = datetime.now().isoformat()
            return vision_results


# 创建全局解析器实例
_supplement_parser_instance = None

def get_supplement_parser() -> SupplementResultParser:
    """
    获取文本补充结果解析器实例（单例模式）
    
    Returns:
        SupplementResultParser: 解析器实例
    """
    global _supplement_parser_instance
    
    if _supplement_parser_instance is None:
        _supplement_parser_instance = SupplementResultParser()
    
    return _supplement_parser_instance


if __name__ == '__main__':
    # 测试代码
    print("SupplementResultParser测试")
    
    # 创建解析器实例
    parser = SupplementResultParser()
    
    # 模拟一个API响应
    mock_response = {
        "choices": [
            {
                "message": {
                    "content": "{\"supplement_fields\": {\"视频类型\": {\"value\": \"生活vlog\", \"confidence\": 95, \"reasoning\": \"根据视频描述和内容判断\"}, \"情感氛围\": {\"value\": \"积极向上\", \"confidence\": 88, \"reasoning\": \"从画面色调和背景音乐判断\"}}, \"overall_analysis\": \"这是一个记录留学生活的积极向上的vlog视频。\"}"
                }
            }
        ]
    }
    
    # 解析结果
    parsed = parser.parse(mock_response)
    print("解析结果:", json.dumps(parsed, ensure_ascii=False, indent=2))
    
    # 测试获取特定字段
    video_type = parser.get_field_by_name(parsed, "视频类型")
    print("视频类型字段:", video_type)
    
    # 测试验证结果
    is_valid = parser.validate_result(parsed)
    print("结果是否有效:", is_valid)
    
    print("测试完成")